//
//  HomeContentController.m
//  万物记
//
//  Created by Ajen on 2019/6/16.
//  Copyright © 2019 Ajen. All rights reserved.
//

#import "HomeContentController.h"
#import "HomeContentCell.h"
#import "UITableView+RowsNumber.h"
#import "AddContentController.h"

@interface HomeContentController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>{
    NSInteger oldPage;
    UILongPressGestureRecognizer *longPress;
    NSIndexPath * changeOldIndex;
    BOOL canAutoScrollList;
    dispatch_source_t autoScrollListTimer;
}

@end

@implementation HomeContentController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    changeOldIndex = nil;
    canAutoScrollList = YES;
    
    longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognized:)];
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView.contentSize = CGSizeMake(self.view.Width * 10, self.view.Height);
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;

    [self.view layoutIfNeeded];

    
    
    [RACObserve(self, homeTitleArray) subscribeNext:^(id x) {
        [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        self.scrollView.contentSize = CGSizeMake(self.view.Width * self.homeTitleArray.count, self.view.Height);
        for(int i = 0 ; i < self.homeTitleArray.count ; i++){
            UITableView * tableView = [[UITableView alloc]initWithFrame:CGRectMake(i * self.scrollView.Width, 0, self.scrollView.Width, self.scrollView.Height) style:UITableViewStylePlain];
            tableView.delegate = self;
            tableView.dataSource = self;
            tableView.showsVerticalScrollIndicator = NO;
            tableView.separatorColor = [UIColor clearColor];
            if (@available(iOS 11.0, *)) {
                tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
                tableView.scrollIndicatorInsets = tableView.contentInset;
            }
            tableView.estimatedRowHeight = 0;
            tableView.estimatedSectionHeaderHeight = 0;
            tableView.estimatedSectionFooterHeight = 0;
            UIView *tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, tableView.bounds.size.width, CGFLOAT_MIN)];
            tableView.tableHeaderView = tableViewHeaderView;
            [self.scrollView addSubview:tableView];
            tableView.tag = 10000 + i;
            RAC(tableView,Height) = RACObserve(self, scrollContentHeight);
            tableView.rowsNumStr = [NSString stringWithFormat:@"%ld",[LocalModel shared].model.Anything[tableView.tag - 10000].contentsList.count];
            AJLog(@"%@",tableView.rowsNumStr);
            
            if(i == 0){
                [tableView addGestureRecognizer:longPress];
            }
            
        }
    }];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if(scrollView == self.scrollView){
        int page = (int)scrollView.contentOffset.x/scrollView.Width+0.5;
        if(self.scrollIndexBlock){
            self.isScrollingList = NO;
            self.scrollIndexBlock(page);
            [self.currentTableView removeGestureRecognizer:longPress];
            [self.currentTableView addGestureRecognizer:longPress];
        }
    }
   
}


-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if(scrollView == self.currentTableView){
        self.isScrollingList = NO;
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.isScrollingList = YES;
    
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return tableView.rowsNumStr.integerValue;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;//如果改这个高度,去HomeController类里面搜索"view.tag = 300000 + originalCellBottom / 100;",顺带把这句也改了
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier =@"HomeContentCell";
    HomeContentCell *cell = [tableView  dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell ==nil){
        cell = [[HomeContentCell alloc]initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if([LocalModel shared].model.Anything[tableView.tag - 10000].contentsList.count){
        cell.itemModel = [LocalModel shared].model.Anything[tableView.tag - 10000].contentsList[indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddContentController * addContentController = [AddContentController new];
    addContentController.editItemModel = [LocalModel shared].model.Anything[tableView.tag - 10000].contentsList[indexPath.row];
    addContentController.editItemIndex = indexPath.row;
    addContentController.tabIndex = self.titleSelectedIndex;
    addContentController.successBlock = ^{
        [tableView reloadData];
    };
    addContentController.deleteBlock = ^(NSInteger deleteIndex) {
        [[LocalModel shared] deleteContentWithTabIndex:_titleSelectedIndex andEditContentListIndex:indexPath.row];
        [self reloadWithAnimationWith:indexPath];
    };
    
    [self.navigationController pushViewController:addContentController animated:YES];

}

-(void)setTitleSelectedIndex:(NSInteger)titleSelectedIndex{
    _titleSelectedIndex = titleSelectedIndex;
    [self.scrollView scrollRectToVisible:CGRectMake(self.scrollView.Width * titleSelectedIndex, 0, self.scrollView.Width, _scrollContentHeight) animated:YES];
    
    [self.currentTableView removeGestureRecognizer:longPress];
    [self.currentTableView addGestureRecognizer:longPress];
}

-(void)reload{
    UITableView * tableView = (UITableView *)[self.view viewWithTag:_titleSelectedIndex + 10000];
    tableView.rowsNumStr = [NSString stringWithFormat:@"%ld",[LocalModel shared].model.Anything[_titleSelectedIndex].contentsList.count];
    [tableView reloadData];
}

-(void)reloadWithAnimationWith:(NSIndexPath *)indexPath{
    UITableView * tableView = (UITableView *)[self.view viewWithTag:_titleSelectedIndex + 10000];
    tableView.rowsNumStr = [NSString stringWithFormat:@"%ld",[LocalModel shared].model.Anything[_titleSelectedIndex].contentsList.count];
    [tableView beginUpdates];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [tableView endUpdates];
}

-(void)setHomeTitleArray:(NSArray *)homeTitleArray{
    _homeTitleArray = homeTitleArray;
}

//设置滚动高度范围
-(void)setScrollContentHeight:(CGFloat)scrollContentHeight{
    _scrollContentHeight = scrollContentHeight;
    self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, _scrollContentHeight);
}


-(UITableView *)currentTableView{
    return (UITableView *)[self.view viewWithTag:_titleSelectedIndex + 10000];
}





- (void)longPressGestureRecognized:(id)sender {
    
    
    
    

    UIGestureRecognizerState state = longPress.state;
//
    CGPoint location = [longPress locationInView:self.currentTableView];
    NSIndexPath *indexPath = [self.currentTableView indexPathForRowAtPoint:location];

    static UIView       *snapshot = nil;        ///< A snapshot of the row user is moving.
    static NSIndexPath  *sourceIndexPath = nil; ///< Initial index path, where gesture begins.
    
    

    switch (state) {
        case UIGestureRecognizerStateBegan: {
            if (indexPath) {
                sourceIndexPath = indexPath;
                if(!changeOldIndex){
                    changeOldIndex = indexPath;
                }
                HomeContentCell *cell = [self.currentTableView cellForRowAtIndexPath:indexPath];

                // Take a snapshot of the selected row using helper method.
                snapshot = [self customSnapshoFromView:cell];

                // Add the snapshot as subview, centered at cell's center...
                __block CGPoint center = cell.center;
                snapshot.center = center;
                snapshot.alpha = 0.0;
                [self.currentTableView addSubview:snapshot];
                [UIView animateWithDuration:0.25 animations:^{

                    // Offset for gesture location.
                    center.y = location.y;
                    snapshot.center = center;
                    snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);
                    snapshot.alpha = 0.98;
                    cell.alpha = 0.0;
                    cell.hidden = YES;

                }];
            }
            break;
        }

        case UIGestureRecognizerStateChanged: {
            kWindow.userInteractionEnabled = NO;
            CGPoint center = snapshot.center;
            center.y = location.y;
            if(center.y - self.currentTableView.contentOffset.y < 50){
                center.y = 50 + self.currentTableView.contentOffset.y;
            }
            
            
            if(center.y > self.currentTableView.contentOffset.y + self.currentTableView.Height - 80){
                if(canAutoScrollList){
                    canAutoScrollList = NO;
                    [self startTabMoveToTop];
                }
            }else if(center.y - self.currentTableView.contentOffset.y  < 80){
                if(canAutoScrollList){
                    canAutoScrollList = NO;
                    [self startTabMoveToBottom];
                }
            }else{
                
                canAutoScrollList = YES;
                [self endTabMoveToTop];
            }
            
            snapshot.center = center;

            if (indexPath && ![indexPath isEqual:sourceIndexPath]) {

                [self.currentTableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];

                sourceIndexPath = indexPath;
            }
            break;
        }
            
        

        default: {
            
            kWindow.userInteractionEnabled = YES;
            //本地数据交换顺序
            [[LocalModel shared]changeContentWithTabIndex:_titleSelectedIndex changeFromIndex:changeOldIndex.row toIndex:indexPath.row];
            
            // Clean up.
            HomeContentCell *cell = [self.currentTableView cellForRowAtIndexPath:sourceIndexPath];
            cell.alpha = 0.0;

            [UIView animateWithDuration:0.25 animations:^{

                snapshot.center = cell.center;
                snapshot.transform = CGAffineTransformIdentity;
                snapshot.alpha = 0.0;
                cell.alpha = 1.0;

            } completion:^(BOOL finished) {

                cell.hidden = NO;
                sourceIndexPath = nil;
                changeOldIndex = nil;
                canAutoScrollList = YES;
                [snapshot removeFromSuperview];
                snapshot = nil;

            }];

            break;
        }
    }
}

- (UIView *)customSnapshoFromView:(UIView *)inputView {
    
    // Make an image from the input view.
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);
    [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Create an image view.
    UIView *snapshot = [[UIImageView alloc] initWithImage:image];
    snapshot.layer.masksToBounds = NO;
    snapshot.layer.cornerRadius = 0.0;
    snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
    snapshot.layer.shadowRadius = 5.0;
    snapshot.layer.shadowOpacity = 0.4;
    
    return snapshot;
}

-(void)startTabMoveToTop{
    if(!autoScrollListTimer && self.currentTableView.contentSize.height >= self.currentTableView.contentOffset.y + self.currentTableView.Height){
        
        autoScrollListTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
        dispatch_source_set_timer(autoScrollListTimer, DISPATCH_TIME_NOW, 0.005 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(autoScrollListTimer, ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                CGFloat x = self.currentTableView.contentOffset.x;
                CGFloat y = self.currentTableView.contentOffset.y;
                self.currentTableView.contentOffset = CGPointMake(x, y+=1);
                if(self.currentTableView.contentOffset.y + self.currentTableView.Height>= self.currentTableView.contentSize.height){
                    [self endTabMoveToTop];
                }
            });
            
        });
        dispatch_resume(autoScrollListTimer);
    }
}
-(void)endTabMoveToTop{
    if(autoScrollListTimer){
        dispatch_source_cancel(autoScrollListTimer);
        autoScrollListTimer = nil;
        AJLog(@"%@",autoScrollListTimer);
    }
}

-(void)startTabMoveToBottom{
    if(!autoScrollListTimer && self.currentTableView.contentOffset.y){
        
        autoScrollListTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
        dispatch_source_set_timer(autoScrollListTimer, DISPATCH_TIME_NOW, 0.005 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(autoScrollListTimer, ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                CGFloat x = self.currentTableView.contentOffset.x;
                CGFloat y = self.currentTableView.contentOffset.y;
                self.currentTableView.contentOffset = CGPointMake(x, y-=1);
                AJLog(@"<<<");
                if(self.currentTableView.contentOffset.y <= 0){
                    [self endTabMoveToBottom];
                }
            });
            
        });
        dispatch_resume(autoScrollListTimer);
    }
}
-(void)endTabMoveToBottom{
    if(autoScrollListTimer){
        dispatch_source_cancel(autoScrollListTimer);
        autoScrollListTimer = nil;
        AJLog(@"%@",autoScrollListTimer);
    }
}

@end
